package com.sf.asp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sf.asp.entity.Role;
import com.sf.asp.dao.RoleMapper;
import com.sf.asp.entity.dto.DeleteDTO;
import com.sf.asp.entity.dto.RoleQueryDTO;
import com.sf.asp.entity.dto.RoleSaveDTO;
import com.sf.asp.entity.vo.PageInfo;
import com.sf.asp.entity.vo.RoleVO;
import com.sf.asp.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jins
 * @since 2021-11-24
 */
@Service
public class RoleServiceImpl implements RoleService {


    private final RoleMapper roleMapper;

    public RoleServiceImpl(RoleMapper roleMapper){
        this.roleMapper = roleMapper;
    }

    @Override
    public PageInfo listRole(RoleQueryDTO roleParam) {
        Page<Role> page = new Page<>(roleParam.getPageNo(),roleParam.getPageSize());

        IPage<Role> rolePage = roleMapper.listRole(page, roleParam);
        List<RoleVO> roleVOS = new ArrayList<>();
        rolePage.getRecords().forEach(role -> {
            RoleVO roleVO = new RoleVO();
            BeanUtils.copyProperties(role,roleVO);
            roleVOS.add(roleVO);
        });

        return new PageInfo(rolePage.getTotal(), roleVOS);
    }

    @Override
    public void saveRole(RoleSaveDTO  roleObj) {
        if(StringUtils.isBlank(roleObj.getRoleName())){
            throw new IllegalArgumentException("角色名必填");
        }
        Role role = new Role();
        role.setName(roleObj.getRoleName());
        role.setStatus(0);
        role.setCreateTime(LocalDateTime.now());
        roleMapper.insert(role);
    }

    @Override
    public void deleteRole(DeleteDTO delete) {
        roleMapper.deleteRole(delete.getIds());
    }

    @Override
    public RoleVO getRoleById(Integer roleId) {
        Role role = roleMapper.selectById(roleId);
        return RoleVO.roleToVo(role);
    }

    @Override
    public void editRole(RoleVO roleVO) {
        Role role = RoleVO.voToRole(roleVO);
        roleMapper.updateById(role);
    }

    @Override
    public List<RoleVO> listRoleForUser() {
        List<Role> roles = roleMapper.selectList(new QueryWrapper<>());
        List<RoleVO> roleVOS = new ArrayList<>();
        roles.forEach(role -> roleVOS.add(RoleVO.roleToVo(role)));
        return roleVOS;
    }

}
